from ywpt.netdevops.models import monitor
from pysnmp.hlapi import *
import datetime
import time

def snmpv2_get(ip, community, oid, port=161):
    errorIndication, errorStatus, errorindex, varBinds = next(
        getCmd(SnmpEngine(),
                CommunityData(community),
                UdpTransportTarget((ip, port)),
                ContextData(),
                ObjectType(ObjectIdentity(oid)),
                )
        )

    # 错误处理
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorindex and varBinds[int(errorindex) - 1][0] or '?'
        )
                )

    # 如果返回结果有多行，需要拼接后返回
    result = ""
    for varBinds in varBinds:
        result = result + varBinds.prettyPrint()

    # 返回的为一个元组，OID与字符串结果
    return result.split("=")[0].strip(), result.split("=")[1].strip()

def get_info_writedb(ip, rocommunity, seconds):
    while seconds >= 0:

        # CPU 5s 利用率
        cpu_info = snmpv2_get(ip, rocommunity, "1.3.6.1.4.1.2011.6.3.4.1.2.0.4.0", 161)[1]
        # 已用内存
        mem_info = snmpv2_get(ip, rocommunity, "1.3.6.1.4.1.2011.6.3.5.1.1.4.0.4.0", 161)[1]
        # 记录当前时间
        time_info = datetime.datetime.now()
        print(time_info)
        monitor.objects.create(cpu_info=cpu_info,mem_info=mem_info,time=time_info)
        time.sleep(5)
    seconds -= 5

if __name__ == "__main__":
    get_info_writedb("10.55.1.200", "Shopeebjsnmp", 2)